package com.castle.fortress.admin.dify.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.dify.model.ContractReviewRequestResult;
import com.castle.fortress.admin.dify.model.ContractReviewResult;
import com.castle.fortress.admin.dify.service.ContractReviewResultService;
import com.castle.fortress.common.entity.RespBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.util.List;
import com.castle.fortress.admin.dify.model.dto.ContractReviewStatistics;
import com.castle.fortress.admin.dify.model.dto.ContractReviewResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/contract-review-results")
public class ContractReviewResultController {

    @Autowired
    private ContractReviewResultService contractReviewResultService;



    @GetMapping("/{id}")
    public ContractReviewResult getById(@PathVariable Long id) {
        return contractReviewResultService.getById(id);
    }

    @GetMapping("/by-review/{reviewId}")
    public ContractReviewResult getByReviewId(@PathVariable Long reviewId) {
        QueryWrapper<ContractReviewResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("review_id", reviewId);
        return contractReviewResultService.getOne(queryWrapper);
    }

    @GetMapping("/page")
    public Page<ContractReviewResult> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return contractReviewResultService.page(new Page<>(current, size));
    }




    @PostMapping
    public boolean save(@RequestBody ContractReviewResult result) {
        return contractReviewResultService.save(result);
    }

    @PutMapping("/{id}")
    public boolean update(@PathVariable Long id, @RequestBody ContractReviewResult result) {
        result.setResultId(id);
        return contractReviewResultService.updateById(result);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return contractReviewResultService.removeById(id);
    }

    /**
     * 获取合同审查结果列表（带统计信息）
     */
    @GetMapping("/listAll")
    public RespBody<ContractReviewResultVO> listAll(ContractReviewResult contractReviewResult) {
        // 构建查询条件
        LambdaQueryWrapper<ContractReviewResult> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (contractReviewResult.getContractId() != null) {
            wrapper.eq(ContractReviewResult::getContractId, contractReviewResult.getContractId());
        }
        
        if (StringUtils.isNotEmpty(contractReviewResult.getRiskLevel())) {
            wrapper.eq(ContractReviewResult::getRiskLevel, contractReviewResult.getRiskLevel());
        }
        
        if (StringUtils.isNotEmpty(contractReviewResult.getRiskStatus())) {
            wrapper.eq(ContractReviewResult::getRiskStatus, contractReviewResult.getRiskStatus());
        }
        
        // 获取列表数据
        List<ContractReviewResult> list = contractReviewResultService.list(wrapper);
        
        // 处理每条记录的risks字段，转换为riskList
        ObjectMapper objectMapper = new ObjectMapper();
        for (ContractReviewResult result : list) {
            try {
                if (StringUtils.isNotEmpty(result.getRisks())) {
                    // 将JSON字符串转换为List<ContractReviewRequestResult>
                    List<ContractReviewRequestResult> riskList = objectMapper.readValue(
                        result.getRisks(),
                        objectMapper.getTypeFactory().constructCollectionType(
                            List.class, 
                            ContractReviewRequestResult.class
                        )
                    );
                    result.setRiskList(riskList);
                }
            } catch (JsonProcessingException e) {
               // log.error("Failed to parse risks JSON for result ID: " + result.getResultId(), e);
                // 设置空列表而不是抛出异常，保证其他数据正常显示
                result.setRiskList(new ArrayList<>());
            }
        }
        
        // 统计风险数据
        ContractReviewStatistics statistics = calculateStatistics(list);
        
        // 构建返回结果
        ContractReviewResultVO result = new ContractReviewResultVO();
        result.setList(list);
        result.setStatistics(statistics);
        
        return RespBody.data(result);
    }

    /**
     * 计算风险统计信息
     */
    private ContractReviewStatistics calculateStatistics(List<ContractReviewResult> list) {
        ContractReviewStatistics statistics = new ContractReviewStatistics();
        
        if (list == null || list.isEmpty()) {
            statistics.setTotal(0);
            statistics.setHigh(0);
            statistics.setMedium(0);
            statistics.setLow(0);
            return statistics;
        }

        int highCount = 0;
        int mediumCount = 0;
        int lowCount = 0;

        for (ContractReviewResult result : list) {
            String riskLevel = result.getRiskLevel();
            if ("HIGH".equalsIgnoreCase(riskLevel)) {
                highCount++;
            } else if ("MEDIUM".equalsIgnoreCase(riskLevel)) {
                mediumCount++;
            } else if ("LOW".equalsIgnoreCase(riskLevel)) {
                lowCount++;
            }
        }

        statistics.setHigh(highCount);
        statistics.setMedium(mediumCount);
        statistics.setLow(lowCount);
        statistics.setTotal(highCount + mediumCount + lowCount);

        return statistics;
    }

}